package com.ys.controller.api.eKnowAi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ys.config.MyConfig;
import com.ys.entity.eKnowAi.*;
import com.ys.enume.eKnowAi.EknowCodeEnum;
import com.ys.service.eKnowAi.EKnowAiService;
import com.ys.util.baidu.ApiHttpClientUtils;
import com.ys.util.RedisUtil;
import com.ys.util.SnowflakeIdWorker;
import com.ys.util.shiro.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/api/inter/eKnowAi")
public class ApiInterEKnowAiController {
	private static final Logger logger = LoggerFactory.getLogger(ApiInterEKnowAiController.class);

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private ApiHttpClientUtils apiHttpUtils;

	private static String URLAPI2_0 = MyConfig.getUrlApi1_5();

	@Autowired
	private EKnowAiService eKnowAiService;

	/*
	 * 获取场景配置信息
	 */
	@PostMapping("/getEKnowSceneSet")
	@ResponseBody
	public JSONObject getEKnowSceneSet(HttpServletRequest request, HttpServletResponse response){
		JSONObject result = new JSONObject();
		try {
			long sceneId = 1L;
			long roleId = ShiroUtils.getRoleId();//用户角色id
			//登录的用户ID
			String loginUserId = ShiroUtils.getUserId();
			EKnowScene eKnowScene = new EKnowScene();
			//获取场景设置信息
			if(!loginUserId.equals("admin")){
				eKnowScene = new EKnowScene()
						.setOrderby("A.Sort ASC")
						.addLeftJoin("kjecp.dbo.YS_Button B ON B.NameShiroAuth = 'eKnowAi:'+A.SceneKey")
						.addLeftJoin("kjecp.dbo.YS_RoleButton R ON R.ButtonId = B.Id")
						.where("R.RoleId = "+roleId)
						.setOrderby("A.Sort ASC")
						.queryFirst();
			}else {
				eKnowScene = new EKnowScene().setOrderby("A.Sort ASC").queryFirst();
			}
			long eKnowSceneSceneId = eKnowScene.getId();
			//获取场景设置信息
			//EKnowScene eKnowScene = new EKnowScene().setId(sceneId).queryFirst();

			//获取用户的对话记录
			List<Map<String,Object>> chatRecord = new ArrayList<>();
			if(eKnowScene.getOpenIsNewChat()==1){//查询设置是否清除对话记录开启新会话
				//清空用户对话记录
				redisUtil.zRemoveRange("EKnowUserChatRecord"+sceneId+loginUserId,0,-1);
				result.put("beginRow", 0);
			}else {//从redis获取用户的对话记录，获取最新10条对话
				if(redisUtil.zSize("EKnowUserChatRecord"+sceneId+loginUserId)!= null && redisUtil.zSize("EKnowUserChatRecord"+sceneId+loginUserId)>0){
					Long userChatRecordCount = redisUtil.zSize("EKnowUserChatRecord"+sceneId+loginUserId);
					chatRecord = getChatRecord(userChatRecordCount-10>0?userChatRecordCount-10:0,userChatRecordCount);
					result.put("beginRow", userChatRecordCount-10);
				}
			}

			//从redis获取用户当天已使用的对话次数
			int chatCount = 0;
			if(redisUtil.hGet("EKnowUserChatCount"+eKnowSceneSceneId,loginUserId)!= null && !redisUtil.hGet("EKnowUserChatCount"+eKnowSceneSceneId,loginUserId).equals("")){
				chatCount = Integer.parseInt(redisUtil.hGet("EKnowUserChatCount"+eKnowSceneSceneId,loginUserId).toString()) ;
			}
			//从redis获取获取用户设置的角色名
			String userSetAiName = "";
			if(redisUtil.hGet("EKnowUserSetAiName"+sceneId,loginUserId)!= null && !redisUtil.hGet("EKnowUserSetAiName"+sceneId,loginUserId).equals("")){
				userSetAiName = redisUtil.hGet("EKnowUserSetAiName"+sceneId,loginUserId).toString();
			}

			List<EKnowModel> modelList = new EKnowModel()
					.addLeftJoin("kjecp_eknow.dbo.EKnow_Scene_Model M ON A.Id = M.ModelId")
					.where("M.SceneId = "+ sceneId)
					.setOrderby("A.Sort ASC")
					.queryList();

			result.put("eKnowScene",eKnowScene);
			result.put("loginUserId",loginUserId);
			result.put("chatRecord",chatRecord);
			result.put("chatCount",chatCount);
			result.put("userSetAiName",userSetAiName);
			result.put("modelList",modelList);
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道聊天获取场景配置信息出错：",e.getMessage(),e);
		}
		return result;
	}

	/**
	 * Ai聊天接口
	 * params：sceneId场景id、isKnowledgeBase是否知识库（0否，1是）、chatMessages对话记录（最多10条）、question用户问题、aiName模型自定义名称
	 */
	@PostMapping("/getAiChat")
	@ResponseBody
	public JSONObject getAiChat( HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			long sceneId = Long.parseLong(params.get("sceneId").toString());//场景id
			long sceneIdBy1 = 1L;//场景id
			long aiModelId = Long.parseLong(params.get("aiModelId").toString());//ai模型id;

			String loginUserId = ShiroUtils.getUserId();//登录的用户ID
			//long timestamp = new Date().getTime() / 1000;//当前时间戳
			SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
			long userChatId = idWorker.nextId();

			EKnowScene eKnowScene = new EKnowScene().setId(sceneId).queryFirst();//获取场景设置信息
			int chatCount = 0;
			//判断当前场景是否限制用户会话次数
			if(eKnowScene.getIsLimitTimes()==1){//如果限制
				//先判断用户当前的会话次数是否超出限制
				int inputMax = eKnowScene.getInputMax();
				//从redis获取用户当天已使用的对话次数
				if(redisUtil.hGet("EKnowUserChatCount"+sceneId,loginUserId)!= null && !redisUtil.hGet("EKnowUserChatCount"+sceneId,loginUserId).equals("")){
					chatCount = Integer.parseInt(redisUtil.hGet("EKnowUserChatCount"+sceneId,loginUserId).toString()) ;
				}
				//如果超出限制，直接返回
				if(chatCount-inputMax>=0){
					result.put("code", EknowCodeEnum.ApiRetuenCode.OVERTIMES);
					return result;
				}
			}

			int isKnowledgeBase = 1;//标识是否用知识库问答，0否1是
			//获取场景设置对应知识库设置
			int knowledgeBaseIsOpen = eKnowScene.getKnowledgeBaseIsOpen();
			if(knowledgeBaseIsOpen==1){//使用知识库问答配置是否开启（0关闭，1开启），若设置关闭，则默认使用知识库问答
				isKnowledgeBase = Integer.parseInt(params.get("isKnowledgeBase").toString());
			}

			Map<String, Object> sendParams = new HashMap<>();
			String sentUrl = URLAPI2_0;
			JSONObject chatBack = new JSONObject();
			//获取对话历史记录
			JSONArray chatMessagesList = new JSONArray();
			if(params.get("chatMessages")!=null){
				chatMessagesList = JSON.parseArray(params.get("chatMessages").toString());
			}
			//sentUrl = sentUrl + "/api/outer/baiDuEKnowAi/ernieBotTurboChat";
			sentUrl = sentUrl + "/api/outer/baiDuEKnowAi/baiDuModelChat";
			sendParams.put("user_id",loginUserId);//提问人
			//设置ai人设
			if(eKnowScene.getAiSystem()!=null && !"".equals(eKnowScene.getAiSystem())){
				String aiSystem = eKnowScene.getAiSystem();
				if (aiSystem.contains("*")) {
					String aiName = eKnowScene.getModelDefaultName();
					if(eKnowScene.getModelRoleIsOpen()==1){
						//从redis获取获取用户设置的角色名
						if(redisUtil.hGet("EKnowUserSetAiName"+sceneIdBy1,loginUserId)!= null && !redisUtil.hGet("EKnowUserSetAiName"+sceneIdBy1,loginUserId).equals("")){
							aiName = redisUtil.hGet("EKnowUserSetAiName"+sceneIdBy1,loginUserId).toString();
						}
					}
					sendParams.put("system",aiSystem.replace("*", aiName));
				}else {
					sendParams.put("system",aiSystem);
				}
			}
			//接口后缀
			EKnowModel eKnowModel = new EKnowModel().setId(aiModelId).queryFirst();
			if(eKnowModel==null){
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
				return result;
			}
			String pathSuffix = eKnowModel.getPathSuffix();
			sendParams.put("pathSuffix",pathSuffix);

			int embeddingTokens = 0;
			String question =params.get("question").toString();
			String useKnowLedge = "";
			if(isKnowledgeBase==0){//不用知识库问答
				/*
				//问题参数
				JSONObject userQuestion = new JSONObject();
				userQuestion.put("role","user");
				userQuestion.put("content",params.get("question"));
				chatMessagesList.add(userQuestion);
				sendParams.put("messages",chatMessagesList);
				//对接Api接口，获取AI回答
				chatBack = apiHttpUtils.sendHttpPost(sendParams,sentUrl);
				 */
				//获取提示词信息
				List<Map<String,Object>> getScenePromptInfo = new EKnowScene()
						.addField("P.PromptContent AS promptContent")
						.addField("K.KeyName AS keyName")
						//.addField("K.IsCanSet AS isCanSet")
						.addField("SP.KeyValue AS keyValue")
						.addLeftJoin("kjecp_eknow.dbo.EKnow_Prompt P ON P.Id = 2 ")
						.addLeftJoin("kjecp_eknow.dbo.EKnow_Scene_PromptKey SP ON SP.SceneId = A.Id AND SP.KeyValue IS NOT NULL ")
						.addLeftJoin("kjecp_eknow.dbo.EKnow_PromptKey K ON SP.KeyId = K.Id")
						.where("A.Id="+sceneId)
						.queryMap();

				if(getScenePromptInfo!=null && getScenePromptInfo.size()>0) {
					String promptContent = getScenePromptInfo.get(0).get("promptContent").toString();
					String promptContentNew = promptContent.replace("{question}", params.get("question").toString());
					for (Map<String, Object> item : getScenePromptInfo) {
						if (item.get("keyValue") != null && !"".equals(item.get("keyValue"))) {
							promptContentNew = promptContentNew.replace("{" + item.get("keyName") + "}", item.get("keyValue").toString());
						} else {
							promptContentNew = promptContentNew.replace("{" + item.get("keyName") + "}", "");
						}
					}
					question = promptContentNew;
				}

			}else {//用知识库问答
				//获取提示词信息
				List<Map<String,Object>> getScenePromptInfo = new EKnowScene()
						.addField("P.PromptContent AS promptContent")
						.addField("K.KeyName AS keyName")
						//.addField("K.IsCanSet AS isCanSet")
						.addField("SP.KeyValue AS keyValue")
						.addLeftJoin("kjecp_eknow.dbo.EKnow_Prompt P ON P.Id = 1 ")
						.addLeftJoin("kjecp_eknow.dbo.EKnow_Scene_PromptKey SP ON SP.SceneId = A.Id AND SP.KeyValue IS NOT NULL ")
						.addLeftJoin("kjecp_eknow.dbo.EKnow_PromptKey K ON SP.KeyId = K.Id")
						.where("A.Id="+sceneId)
						.queryMap();
				//获取知识库信息
				List<Map<String,Object>> getSceneKnowledgeInfo = new EKnowScene()
						.addField("K.ESIndexName As esIndexName")
						.addField("SK.KnowledgeBaseId As knowledgeBaseId")
						.addLeftJoin("kjecp_eknow.dbo.EKnow_Scene_Knowledge SK ON A.Id = SK.SceneId")
						.addLeftJoin("kjecp_eknow.dbo.EKnow_KnowledgeBase K ON K.Id = SK.KnowledgeBaseId")
						.where("A.Id="+sceneId)
						.queryMap();

				if(getScenePromptInfo!=null && getScenePromptInfo.size()>0 && getSceneKnowledgeInfo!=null && getSceneKnowledgeInfo.size()>0){
					String promptContent = getScenePromptInfo.get(0).get("promptContent").toString();
					String information = "";

					String getKnowledgeUrl = URLAPI2_0 + "/api/outer/baiDuEKnowAi/searchKnowledgeList";
					Map<String, Object> sendParamsBygetKnowledge = new HashMap<>();
					List<String> informationList = new ArrayList<>();
					informationList.add(params.get("question").toString());//问题
					List<String> indexNameList = new ArrayList<>();
					for(Map<String,Object> item : getSceneKnowledgeInfo){
						indexNameList.add(item.get("esIndexName").toString());
						//记录所用知识库id列表
						if(useKnowLedge == null || useKnowLedge.equals("")){
							useKnowLedge =  item.get("knowledgeBaseId").toString();
						}else {
							useKnowLedge = useKnowLedge + ","+ item.get("knowledgeBaseId");
						}

					}

					sendParamsBygetKnowledge.put("information",informationList);//问题
					sendParamsBygetKnowledge.put("size",eKnowScene.getEmbeddingBackCount());//向量数据库调用个数
					sendParamsBygetKnowledge.put("score",eKnowScene.getEmbeddingBackSource());//置信度
					sendParamsBygetKnowledge.put("indexNameList",indexNameList);//知识库索引名称
					//向量数据库获取向量数据接口
					JSONObject embeddingBack = apiHttpUtils.sendHttpPost(sendParamsBygetKnowledge,getKnowledgeUrl);
					if(embeddingBack.get("shardIdList")!=null){
						logger.info("向量数据库获取向量数据接口返回参数："+embeddingBack);
						embeddingTokens = Integer.parseInt(embeddingBack.get("totalTokens").toString());//向量化花费的tokens数

						String shardId = null;
						List<Map<String,Object>> shardIdList = (List<Map<String,Object>>)embeddingBack.get("shardIdList");
						if(shardIdList.size()>0){
							for( Map<String,Object> item:shardIdList ){
								if(shardId == null || shardId.equals("")){
									shardId =  "'"+item.get("id").toString()+ "'";
								}else {
									shardId = shardId + ",'"+ item.get("id").toString()+ "'";
								}
							}
							List<EKnowKnowledgeList> getSceneKnowledgeList = new EKnowKnowledgeList().where("A.ESId IN ("+shardId+")").queryList();
							if(getSceneKnowledgeList!=null && getSceneKnowledgeList.size()>0){
								for( EKnowKnowledgeList eKnowKnowledgeList:getSceneKnowledgeList ){
									information = information + "-\n"+ eKnowKnowledgeList.getInformation()+"\n";
								}
							}
						}
					}

					if(!"".equals(information)){
						String promptContentNew = promptContent.replace("{information}", information)
								.replace("{question}", params.get("question").toString());
						for(Map<String,Object> item : getScenePromptInfo){
							if(item.get("keyValue")!=null && !"".equals(item.get("keyValue"))){
								promptContentNew = promptContentNew.replace("{"+item.get("keyName")+"}", item.get("keyValue").toString());
							}else {
								promptContentNew = promptContentNew.replace("{"+item.get("keyName")+"}", "");
							}
						}
						question = promptContentNew;
					}
				}
				/*百度插件问答接口--保留，后续可能有其他插件
				sentUrl = sentUrl + "/api/outer/baiDuEKnowAi/ernieBotTurboChatWithKnowLadge";
				sendParams.put("query",params.get("question"));
				//获取知识库列表
				List<Map<String,Object>> eKnowSceneKnowledgeList = new EKnowSceneKnowledge()
						.setSceneId(eKnowScene.getId())
						.addField("B.BaiduUid AS baiduUid")
						.addLeftJoin("kjecp_eknow.dbo.EKnow_KnowledgeBase B ON A.KnowledgeBaseId = B.Id")
						.queryMap();
				//如果为空，直接返回
				if(eKnowSceneKnowledgeList==null || eKnowSceneKnowledgeList.size()<=0){
					result.put("code", EknowCodeEnum.ApiRetuenCode.NOSET);
					return result;
				}
				List<String> plugins = new ArrayList<>();
				for(Map<String,Object> item:eKnowSceneKnowledgeList){
					//plugins.add(item.get("baiduUid")+"-zhishiku");
					plugins.add("uuid-zhishiku");
				}
				sendParams.put("plugins",plugins);
				sendParams.put("history",chatMessagesList);
				sendParams.put("pathSuffix",eKnowScene.getKnowledgeBasePath());
				//对接Api接口，获取AI回答
				chatBack = apiHttpUtils.sendHttpPost(sendParams,sentUrl);
				 */
			}
			//问题参数
			JSONObject userQuestion = new JSONObject();
			userQuestion.put("role","user");
			userQuestion.put("content",question);
			chatMessagesList.add(userQuestion);
			sendParams.put("messages",chatMessagesList);
			//对接Api接口，获取AI回答
			chatBack = apiHttpUtils.sendHttpPost(sendParams,sentUrl);


			logger.info("聊天接口返回："+chatBack);
			if(chatBack.get("error_code")!=null){
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
				return result;
			}
			if(chatBack!=null){
				//获取返回参数
				String baiDuChatId = (String) chatBack.get("id");//本轮对话的id(百度千帆会话Id)
				int created = Integer.parseInt(chatBack.get("created").toString()) ;//时间戳
				String answer =  chatBack.get("result").toString();//回答
				logger.info("回答："+answer);
				JSONObject usage = (JSONObject) chatBack.get("usage");//token统计信息
				//int prompt_tokens = Integer.parseInt(usage.get("prompt_tokens").toString()) ;//问题tokens数
				//int completion_tokens = Integer.parseInt(usage.get("completion_tokens").toString()) ;//回答tokens数
				int total_tokens = Integer.parseInt(usage.get("total_tokens").toString()) ;//tokens总数

				//数据库会话日志记录
				EKnowChatLog eKnowChatLog = new EKnowChatLog();

				eKnowChatLog.setSceneId(sceneId);//场景id
				eKnowChatLog.setAiModelId(aiModelId);//ai模型id
				eKnowChatLog.setKnowledgeBaseId(useKnowLedge);//知识库
				// 获取会话id

				long  chatidL = idWorker.nextId();
				double chatid = (double) chatidL;

				//记录会话次数
				redisUtil.hPut("EKnowUserChatCount"+sceneId,loginUserId,(chatCount+1)+"");//记录会话次数

				LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
				long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight);
				redisUtil.expire("EKnowUserChatCount"+sceneId,seconds,TimeUnit.SECONDS);//设置过期时间

				ObjectMapper objectMapper = new ObjectMapper();
				//redis更新用户会话记录
				//role角色（user，assistant），content内容，evaluate评价(role是user时为-1，-1也表示未评价)，chatId会话id(role是user时为-1)
				//用户提问记录
				Map<String,Object> inputMapUser = new HashMap<>();
				inputMapUser.put("role","user");
				inputMapUser.put("content",params.get("question").toString());//用户问题
				inputMapUser.put("evaluate","-1");
				inputMapUser.put("chatId",userChatId);
				inputMapUser.put("baiDuChatId",baiDuChatId);
				//参数格式转换
				String inputMsg = objectMapper.writeValueAsString(inputMapUser);
				redisUtil.zAdd("EKnowUserChatRecord"+sceneIdBy1+loginUserId,inputMsg, (double) userChatId);
				//AI回答记录
				Map<String,Object> inputMapAssistant = new HashMap<>();
				inputMapAssistant.put("role","assistant");
				inputMapAssistant.put("content",answer);//AI回答
				inputMapAssistant.put("evaluate","-1");
				inputMapAssistant.put("chatId",chatid+"");//会话id
				inputMapAssistant.put("baiDuChatId",baiDuChatId);//百度会话id
				//参数格式转换
				String inputMsgAssistant = objectMapper.writeValueAsString(inputMapAssistant);
				redisUtil.zAdd("EKnowUserChatRecord"+sceneIdBy1+loginUserId,inputMsgAssistant, chatid);

				//数据库表新增
				eKnowChatLog.setChatId(chatid+"");//会话id
				eKnowChatLog.setBaiDuChatId(baiDuChatId);//百度千帆会话Id
				//eKnowChatLog.setPromptId(eKnowScene.getPromptId());//提示词模版id
				eKnowChatLog.setQuestion(params.get("question").toString());//用户问题
				eKnowChatLog.setAnswer(answer);//回答
				eKnowChatLog.setAnswerUserId("0");//回答用户id,默认ai
				eKnowChatLog.setTokensCount(total_tokens);//token统计信息，token数 = 汉字数+单词数*1.3
				eKnowChatLog.setBaiDuCreated(created);//百度返回的时间戳
				eKnowChatLog.setIsReSet(0);//是否被提取至管理（0未被，1已被）
				eKnowChatLog.setUserId(loginUserId);//用户id
				eKnowChatLog.setIsKnowledge(isKnowledgeBase);//是否用知识库问答（0否，1是，null未记录）
				eKnowChatLog.setWholeSendMsg(question);//完整发送参数，包含知识库返回、提示词
				if(isKnowledgeBase==1)eKnowChatLog.setKnowledgeToken(embeddingTokens);//调用知识库所用的token数
				eKnowChatLog.setStatus(0);
				eKnowAiService.addChatLog(eKnowChatLog);

				result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
				result.put("answer", answer);
				result.put("chatId", chatid);
				result.put("baiDuChatId", baiDuChatId);
				result.put("created", created);
				return result;
			}else {
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
				return result;
			}
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("Ai聊天接口出错：",e.getMessage(),e);
		}
		return result;

	}



	/**
	 * 设置用户自定义AI名字接口
	 * params aiModelName 自定义AI模型名称
	 */
	@PostMapping("/setAiModelName")
	@ResponseBody
	public JSONObject setAiModelName(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try{
			long sceneId = 1L;
			String loginUserId = ShiroUtils.getUserId();//登录的用户ID
			if(params.get("aiModelName")!=null){
				redisUtil.hPut("EKnowUserSetAiName"+sceneId,loginUserId,params.get("aiModelName")+"");//自定义AI模型名称
				result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			}else {
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			}
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("设置用户自定义AI名字接口出错：",e.getMessage(),e);
		}
		return result;
	}


	/**
	 * 点赞、点踩反馈接口
	 * params :evaluate 用户评价反馈，chatId 会话id ,baiDuChatId 百度会话id
	 */
	@PostMapping("/setEvaluate")
	@ResponseBody
	public JSONObject setEvaluate(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try{
			long sceneIdBy1 = 1L;
			String loginUserId = ShiroUtils.getUserId();//登录的用户ID
			if(params.get("evaluate")!=null && params.get("chatId")!=null){
				double chatId = Double.parseDouble(params.get("chatId").toString());
				//获取
				Set<String> chatMsg = redisUtil.zRangeByScore("EKnowUserChatRecord"+sceneIdBy1+loginUserId,chatId,chatId);
				String recordMsg = null;
				for(String recordItem : chatMsg){
					recordMsg = recordItem;
				}
				//先删除
				redisUtil.zRemoveRangeByScore("EKnowUserChatRecord"+sceneIdBy1+loginUserId,chatId,chatId);
				ObjectMapper objectMapper = new ObjectMapper();
				JSONObject recordJson = JSON.parseObject(recordMsg);
				//新增AI回答记录
				Map<String,Object> inputMapAssistant = new HashMap<>();
				inputMapAssistant.put("role","assistant");
				inputMapAssistant.put("content",recordJson.get("content"));//AI回答
				inputMapAssistant.put("evaluate",params.get("evaluate"));
				inputMapAssistant.put("chatId",recordJson.get("chatId"));//会话id
				//参数格式转换
				String inputMsgAssistant = objectMapper.writeValueAsString(inputMapAssistant);
				//redis更新
				redisUtil.zAdd("EKnowUserChatRecord"+sceneIdBy1+loginUserId,inputMsgAssistant, chatId);
				//数据库更新
				EKnowChatLog entity = new EKnowChatLog();
				entity.setEvaluate(params.get("evaluate").toString());
				entity.setChatId(params.get("chatId").toString());
				entity.setBaiDuChatId(params.get("baiDuChatId").toString());

				eKnowAiService.updateChatLog(entity);
				result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			}else {
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			}
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("点赞、点踩反馈接口出错：",e.getMessage(),e);
		}
		return result;
	}


	/**
	 * 聊天记录获取,分页，每页10条
	 * params beginRow开始条数
	 */
	@PostMapping("/getMoreChatRecord")
	@ResponseBody
	public JSONObject getMoreChatRecord(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try{
			long sceneId = 1L;
			String loginUserId = ShiroUtils.getUserId();//登录的用户ID
			//long page = Long.parseLong(params.get("page").toString());//页数
			long beginRow = Long.parseLong(params.get("beginRow").toString());//开始条数
			List<Map<String,Object>> chatRecord = new ArrayList<>();
			if(beginRow!=0 && redisUtil.zSize("EKnowUserChatRecord"+sceneId+loginUserId)!= null && redisUtil.zSize("EKnowUserChatRecord"+sceneId+loginUserId)>0){
				chatRecord = getChatRecord(beginRow-10>0?beginRow-10:0,beginRow-1);
				result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
				result.put("chatRecord", chatRecord);
				result.put("beginRow", beginRow-10);
			}else{
				result.put("code", EknowCodeEnum.ApiRetuenCode.NOMORE);
			}
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error(" 聊天记录获取,分页，每页10条接口出错：",e.getMessage(),e);
		}
		return result;
	}


	/**
	 * 获取聊天记录获取,分页获取公共类
	 * @param start
	 * @param end
	 * @return
	 */
	public List<Map<String,Object>> getChatRecord(long start, long end){
		long sceneId = 1L;
		String loginUserId = ShiroUtils.getUserId();//登录的用户ID
		//从redis获取用户的对话记录，获取最新10条对话
		List<Map<String,Object>> chatRecord = new ArrayList<>();
		if(redisUtil.zSize("EKnowUserChatRecord"+sceneId+loginUserId)!= null && redisUtil.zSize("EKnowUserChatRecord"+sceneId+loginUserId)>0){
			Set<String> userChatRecord = redisUtil.zRange("EKnowUserChatRecord"+sceneId+loginUserId,start,end);
			if(userChatRecord!=null){
				for(String recordItem : userChatRecord){
					//role角色（user，assistant），content内容，evaluate评价(role是user时为-1，-1也表示未评价)，chatId会话id(role是user时为-1)
					JSONObject recordItemJson = JSON.parseObject(recordItem);
					Map<String,Object> item = new HashMap<>();
					item.put("role",recordItemJson.get("role"));
					item.put("content",recordItemJson.get("content"));
					item.put("evaluate",recordItemJson.get("evaluate"));
					item.put("chatId",recordItemJson.get("chatId"));
					item.put("baiDuChatId",recordItemJson.get("baiDuChatId"));
					chatRecord.add(item);
				}
			}
		}
		return chatRecord;
	}


	/**
	 * 清空对话，开启新聊天接口
	 */
	@PostMapping("/cleanChatRecord")
	@ResponseBody
	public JSONObject cleanChatRecord(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params) {
		JSONObject result = new JSONObject();
		try{
			long sceneId = 1L;
			String loginUserId = ShiroUtils.getUserId();//登录的用户ID
			redisUtil.zRemoveRange("EKnowUserChatRecord"+sceneId+loginUserId,0,-1);
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error(" 清空对话，开启新聊天接口出错：",e.getMessage(),e);
		}
		return result;
	}



	/**
	 * 获取提示词信息
	 */
	@PostMapping("/getEKnowTemplateBySceneId")
	@ResponseBody
	public JSONObject getEKnowTemplateBySceneId(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params) {
		JSONObject result = new JSONObject();
		try{
			long sceneId = Long.parseLong(params.get("sceneId").toString());
			List<EKnowTemplate> eKnowTemplateList = new EKnowTemplate()
					.setSceneId(sceneId)
					.setOrderby("A.UpdateTime DESC")
					.queryList();
			List<EKnowTemplateType> eKnowTemplateTypeList = new EKnowTemplateType()
					.setSceneId(sceneId)
					.setOrderby("A.Sort ASC")
					.queryList();
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			result.put("eKnowTemplateList", eKnowTemplateList);
			result.put("eKnowTemplateTypeList", eKnowTemplateTypeList);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("获取提示词信息接口出错：",e.getMessage(),e);
		}
		return result;
	}


}